<template>
	<view class="page" :style="'background-image: url('+indexBg+');'">
    <u-navbar :fixed="false" title="权限管理" placeholder bgColor="transparent"></u-navbar>
    <view class="form-info">
      <view class="form-box u-m-b-48">
        <view class="form-item">
          <view class="form-lable required">角色名称</view>
          <view class="form-content">
            <u--input tye="number" placeholder="请输入" :maxlength="11" border="none" inputAlign="right" v-model="form.roleName" />
          </view>
        </view>
        <view class="form-item">
          <view class="form-lable">功能权限</view>
          <view class="form-content-right">
            <u--text class="u-m-r-20" type="primary" text="WEB端权限" @click="getMenuList('1')"></u--text>
            <u--text type="primary" text="小程序权限" @click="getMenuList('2')"></u--text>
          </view>
        </view>
      </view>
      <view class="save-primary-btn" @click="submit">保存提交</view>
    </view>
    <peng-tree
      ref="pengTree"
      :showTree="treeOpen"
      :range="menuOptions"
      idKey="menuId"
      nameKey="menuName"
      allKey="menuId"
      :multiple="true"
      :cascade="false"
      :selectParent="true"
      :foldAll="false"
      confirmColor="#007aff"
      cancelColor="#757575"
      title="功能权限"
      titleColor="#757575"
      @cancel="treeCancel"
      @confirm="treeConfirm"
    >
    </peng-tree>
  </view>
</template>

<script>
import { getSystemAllMenu, getAppletAllMenu, getPlatformRole, addPlatformRole, updatePlatformRole } from '@/api/index'

export default {
  data() {
    return {
      indexBg: 'https://gowork365.com/prod-api/profile/mini/index/indexBg1.png',
      id: '',
      form: {
        roleName: '',
      },
      defaultForm: {
        roleName: '',
      },
      menuType: '',
      menuOptions: [],
      getMenuAllCheckedKeys1: [],
      getMenuAllCheckedKeys2: [],
      treeOpen: false,
    }
  },
  onLoad(options) {
    if(options.id) {
      this.id = options.id
      this.getForm()
    }
  },
  methods: {  
    treeCancel(e) {
      this.treeOpen = false
    },
    treeConfirm(e) {
      if(this.menuType == '1') {
        this.getMenuAllCheckedKeys1 = e.map(v => v.id)
      } else {
        this.getMenuAllCheckedKeys2 = e.map(v => v.id)
      }
      this.treeOpen = false
    },
    getMenuList(menuType) {
      uni.showLoading({ mask: true })
      this.menuType = menuType
      if(this.menuType == '1') {
        getSystemAllMenu().then(response => {
          uni.hideLoading()
          this.menuOptions = this.buildTree(response.data)
          this.treeOpen = true
        })
      } else {
        getAppletAllMenu().then(response => {
          uni.hideLoading()
          this.menuOptions = this.buildTree(response.data)
          this.treeOpen = true
        })
      }
    },
    buildTree(data, rootId = '0') {
      const map = new Map();
      const result = [];

      // 初始化 map，每个节点预设 children 为 []
      data.forEach(item => {
        item.children = [];
        map.set(item.menuId, item);
      });

      data.forEach(item => {
        if (item.parentId === rootId) {
          result.push(item);
        } else {
          const parent = map.get(item.parentId);
          if (parent) {
            parent.children.push(item);
          } else {
            result.push(item);
          }
        }
      });
      return result;
    },
    getForm() {
      uni.showLoading({ mask: true })
      getPlatformRole(this.id).then(response => {
        uni.hideLoading()
        if(response.data.roleKey) {
          response.data.roleKey = response.data.roleKey.split(',')
        }
        this.getMenuAllCheckedKeys = response.data.roleKey || []
        this.form = response.data;
      });
    },
    submit() {
      const that = this
      let formFlag = false
      for(let key in this.defaultForm) {
        if(this.form[key] === '') {
          formFlag = true
        }
      }
      if(formFlag) {
        uni.showToast({
          icon: 'none',
          title: '请完善基本信息'
        })
        return
      }
      if(this.getMenuAllCheckedKeys.length == 0) {
        uni.showToast({
          icon: 'none',
          title: '请选择菜单权限'
        })
        return
      }
      const pcMenuList = this.getMenuAllCheckedKeys1;
      const appletMenuList = this.getMenuAllCheckedKeys2;
      uni.showLoading({ mask: true })
      if (this.form.id != null) {
        updatePlatformRole({...this.form, pcMenuList, appletMenuList}).then(response => {
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            title: '修改成功'
          })
          setTimeout(() => {
            that.goBack(1)
          }, 1000)
        });
      } else {
        addPlatformRole({...this.form, pcMenuList, appletMenuList}).then(response => {
          uni.hideLoading()
          uni.showToast({
            icon: 'none',
            title: '新增成功'
          })
          setTimeout(() => {
            that.goBack(1)
          }, 1000)
        });
      }
    }
  }
}
</script>

<style lang="less" scoped>
.page {
  width: 100%;
  min-height: 100vh;
  background: #F4F7F6;
  position: relative;
  background-repeat: no-repeat;
  background-size: 750rpx 690rpx;
  padding-bottom: 188rpx;
  display: flex;
  flex-direction: column;
  .form-info {
    flex: 1;
  }
}
</style>
